package cn.edik;

import cn.edik.kit.ConfigKey;
import cn.edik.kit.ConfigKit;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;


public class Main {

    @FXML
    private Pane rootLayout;

    @FXML
    private TextField sharedFolders;

    @FXML
    private CheckBox authCheckBox;

    @FXML
    private Circle serverState;

    @FXML
    private TextField username;
    @FXML
    private TextField password;
    @FXML
    private TextField portTextField;
    @FXML
    private TextField linkTextField;

    @FXML
    private Hyperlink ftpLink;
    @FXML
    private Button copyFtpLinkBtn;

    private static Boolean started = false;

    public Main() {
        System.out.println("控制器初始化");
    }

    @FXML
    public void initialize() {
        System.out.println("界面初始化");
        portTextField.setText(ConfigKit.get(ConfigKey.PORT, "21"));
        linkTextField.setText(ConfigKit.get(ConfigKey.MAXLINK, "100"));
        sharedFolders.setText(ConfigKit.get(ConfigKey.SHAREDFOLDER, ""));
        username.setText(ConfigKit.get(ConfigKey.USERNAME, ""));
        password.setText(ConfigKit.get(ConfigKey.PASSWORD, ""));

        authCheckBox.setSelected(ConfigKit.getBoolean(ConfigKey.CHECKUSER, false));
        if(ConfigKit.getBoolean(ConfigKey.CHECKUSER, false)){
            username.setDisable(false);
            password.setDisable(false);
        }

        setFtpLink("", false);
    }

    @FXML
    public void authentication(ActionEvent event) {
        CheckBox checkBox = (CheckBox) event.getSource();

        if (checkBox.isSelected()) {
            // 校验身份
            username.setDisable(false);
            password.setDisable(false);
        } else {
            // 不校验身份
            username.setDisable(true);
            password.setDisable(true);
        }
    }

    @FXML
    public void startBtnClick(ActionEvent event) {
        Button btnSource = (Button) event.getSource();

        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误信息");
        alert.setHeaderText(null);

        boolean selected = authCheckBox.isSelected();

        if (!started) {
            String port = portTextField.getText();

            String sharedFoldersText = sharedFolders.getText();

            if ("".equals(port)) {
                alert.setContentText("端口不能为空");
                alert.showAndWait();
                return;
            }

            if ("".equals(sharedFoldersText)) {
                alert.setContentText("共享目录不能为空");
                alert.showAndWait();
                return;
            } else {
                try {
                    if (!(new File(sharedFoldersText).isDirectory())) {
                        new File(sharedFoldersText).mkdirs();
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                    alert.setContentText("路径不正确");
                    alert.showAndWait();
                    return;
                }
            }

            ConfigKit.put(ConfigKey.PORT, port);
            ConfigKit.put(ConfigKey.SHAREDFOLDER, sharedFoldersText);
            ConfigKit.putBoolean(ConfigKey.CHECKUSER, selected);

            if (selected) {
                String usernameText = username.getText();
                String passwordText = password.getText();
                if ("".equals(usernameText) || "".equals(passwordText)) {
                    alert.setContentText("用户名或密码不能为空");
                    alert.showAndWait();
                    return;
                }


                ConfigKit.put(ConfigKey.USERNAME, usernameText);
                ConfigKit.put(ConfigKey.PASSWORD, passwordText);
                FTP.start(Integer.parseInt(port), usernameText, passwordText, sharedFoldersText);
            } else {
                FTP.start(Integer.parseInt(port), "anonymous", "", sharedFoldersText);
            }

            started = true;
            btnSource.setText("停止服务");

            serverState.setFill(Color.CHARTREUSE);

            InetAddress ia = null;
            try {
                ia = ia.getLocalHost();

                String localname = ia.getHostName();
                String localip = ia.getHostAddress();
//                System.out.println("本机名称是：" + localname);
//                System.out.println("本机的ip是 ：ftp://" + localip);
                setFtpLink("ftp://" + localip, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            FTP.stop();
            started = false;
            btnSource.setText("启动服务");
            serverState.setFill(Color.RED);
            setFtpLink("", false);
        }


    }

    @FXML
    public void stopBtnClick(ActionEvent event) {

    }

    @FXML
    public void chooseBtnClick(ActionEvent event) {
        Stage stage = (Stage) rootLayout.getScene().getWindow();

        DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(stage);

        if (null != file) {
            String path = file.getPath();//选择的文件夹路径
            sharedFolders.setText(path);
        }

    }

    @FXML
    public void openEdik(ActionEvent event) {
        Hyperlink hyperlink = (Hyperlink) event.getSource();

        String text = hyperlink.getText();
        try {
            Desktop.getDesktop().browse(new URI(text));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    @FXML
    public void copyFtpLink(ActionEvent event) {
        String ftpLinkText = ftpLink.getText();

        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(ftpLinkText);
        clip.setContents(tText, null);
    }

    public void setFtpLink(String text, boolean show) {
        ftpLink.setText(text);
        ftpLink.setVisible(show);
        ftpLink.setManaged(show);
        copyFtpLinkBtn.setVisible(show);
        copyFtpLinkBtn.setManaged(show);
    }

    @FXML
    public void goFtp(ActionEvent event) {
        String text = ftpLink.getText();
        try {
            Desktop.getDesktop().browse(new URI(text));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }


}
